package com.xt.tea.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xt.tea.constant.AuthConstant;
import com.xt.tea.entity.bo.OrderBo;
import com.xt.tea.entity.domain.*;
import com.xt.tea.entity.enums.RequestResultEnum;
import com.xt.tea.entity.exception.GlobalException;
import com.xt.tea.entity.vo.Condition;
import com.xt.tea.entity.vo.OrderVo;
import com.xt.tea.mapper.OrderMapper;
import com.xt.tea.mapper.TeaMapper;
import com.xt.tea.service.OrderService;
import com.xt.tea.utils.TokenUtil;
import lombok.AllArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Service
@AllArgsConstructor
public class OrderServiceImpl extends BaseService implements OrderService {

    private final OrderMapper orderMapper;

    private final WorkService workService;

    private final TeaMapper teaMapper;
    @Override
    public IPage<OrderBo> getOrderByCondition(Condition<Order> condition) {
        if (condition==null){
            throw new GlobalException(RequestResultEnum.CUSTOM_PARAM_CHECK_FAILED);
        }
        Page<Order> page = Page.of(condition.getPageIndex(), condition.getPageSize());
        LambdaQueryWrapper<Order> queryWrapper = new LambdaQueryWrapper<>();
        if (condition.getQueryInfo()!=null){
            Order queryInfo = condition.getQueryInfo();
            if (queryInfo.getToken()!=null){
                String roleIdByToken = TokenUtil.getRoleIdByToken(queryInfo.getToken());
                if (!Objects.equals("2",roleIdByToken)){
                    queryWrapper.eq(Order::getUid,TokenUtil.getUserIdByToken(queryInfo.getToken()));
                }
            }
        }
        Page<Order> orderPage = orderMapper.selectPage(page, queryWrapper);
        Page<OrderBo> result = new Page<>();
        result.setTotal(orderPage.getTotal());
        result.setRecords(new ArrayList<>());
        if (result.getTotal()>0){
            for (Order record : orderPage.getRecords()) {
                OrderBo orderBo = new OrderBo();
                BeanUtils.copyProperties(record,orderBo);
                //填充用户名
                User user = workService.getUserById(record.getUid());
                if (user!=null){
                    orderBo.setUserName(user.getUserName());
                }
                //填充桌号
                Desk desk = workService.getDeskById(record.getDid());
                if (desk!=null){
                    orderBo.setDeskNo(desk.getDeskNo());
                }
                //填充订单详情
                String orderMessage = record.getOrderMessage();
                List<?> teaOrders = JSON.parseObject(orderMessage, List.class);
                record.setTeaOrders(new ArrayList<>());
                orderBo.setTeaMsg(new ArrayList<>());
                if (teaOrders!=null&&teaOrders.size()>0){
                    for (Object teaOrder1 : teaOrders) {
                        String teaOrderString = String.valueOf(teaOrder1);
                        TeaOrder teaOrder = JSON.parseObject(teaOrderString, TeaOrder.class);
                        Tea tea = workService.getTeaById(teaOrder.getId());
                        orderBo.getTeaMsg().add(String.format(AuthConstant.ORDER_FORMAT,tea.getTeaName(),teaOrder.getSelectCount(),teaOrder.getPrice().multiply(new BigDecimal(teaOrder.getSelectCount()))));
                    }
                }
                orderBo.setPrice(record.getTotalPrice());
                result.getRecords().add(orderBo);
            }
        }
        return result;
    }

    public OrderVo addOrder(OrderVo orderVo){
        String userIdByToken = TokenUtil.getUserIdByToken(orderVo.getToken());
        Order order = new Order();
        BeanUtils.copyProperties(orderVo,order);
        order.setUid(Integer.parseInt(userIdByToken));
        BigDecimal total = new BigDecimal(0);
        for (TeaOrder teaOrder : order.getTeaOrders()) {
            BigDecimal multiply = teaOrder.getPrice().multiply(new BigDecimal(teaOrder.getSelectCount()));
            total=total.add(multiply);
        }
        order.setTotalPrice(total);
        List<String> result = new ArrayList<>();
        if (order.getTeaOrders()!=null&&order.getTeaOrders().size()>0){
            for (TeaOrder teaOrder : order.getTeaOrders()) {
                Tea tea = this.selectById(teaMapper, teaOrder.getId());
                tea.setCount(tea.getCount()-teaOrder.getSelectCount());
                teaMapper.updateById(tea);
                result.add(JSON.toJSONString(teaOrder));
            }
        }
        order.setOrderMessage(JSON.toJSONString(result));
        this.insert(orderMapper,order);
        //订单减库存
        return orderVo;
    }

    public Order deleteOrder(Order order){return deleteOrder(order);}


}
